<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" top="20px">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="140px">
      <el-form-item prop="name" :label="$t('company.name')">
        <el-input v-model="dataForm.name" :placeholder="$t('company.name')" :disabled="this.dataForm.id > 0"/>
      </el-form-item>
      <el-form-item prop="regCode" :label="$t('company.regCode')">
        <el-input v-model="dataForm.regCode" :placeholder="$t('company.regCode')"/>
      </el-form-item>
      <el-form-item prop="legalPerson" :label="$t('company.legalPerson')">
        <el-input v-model="dataForm.legalPerson" :placeholder="$t('company.legalPerson')"/>
      </el-form-item>
      <el-form-item prop="legalPersonIdentity" :label="$t('company.legalPersonIdentity')">
        <el-input v-model="dataForm.legalPersonIdentity" :placeholder="$t('company.legalPersonIdentity')"/>
      </el-form-item>
      <el-form-item prop="legalPersonMobile" :label="$t('company.legalPersonMobile')">
        <el-input v-model="dataForm.legalPersonMobile" :placeholder="$t('company.legalPersonMobileDes')" />
      </el-form-item>
      <el-form-item prop="contactMobile" :label="$t('company.contactMobile')">
        <el-input v-model="dataForm.contactMobile" :placeholder="$t('company.contactMobile')" />
      </el-form-item>
      <el-form-item prop="contractCode" :label="$t('company.contractCode')">
        <el-input v-model="dataForm.contractCode" :placeholder="$t('company.contractCode')" style="width: 280px; margin-right: 8px;" />如:湖北武汉 HB-WH
      </el-form-item>
      <el-form-item prop="paymentMethod" :label="$t('company.paymentMethod')">
        <el-select v-model="dataForm.paymentMethod" :value="dataForm.paymentMethod"
                   placeholder="请选择付费方式"
                   style=" width: 180px;">
          <el-option
                  v-for="item in paymentMethodOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="paymentType" label="付费类型">
        <el-select v-model="dataForm.paymentType" :value="dataForm.paymentType"
                   placeholder="请选择付费类型"
                   style=" width: 180px;">
          <el-option
                  v-for="item in paymentTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
          </el-option>
        </el-select>
        <el-button v-if="dataForm.paymentType === 2" icon="el-icon-plus" circle @click="addCompanyPaymentType" size="mini" style="margin-left: 20px"></el-button>
      </el-form-item>
      <el-row v-if="dataForm.paymentType === 2" style="box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3); padding: 15px 0 15px 20px; margin: 15px">
        <el-row v-for="(item, index) in dataForm.companyPaymentTypes" :key="index">
          合同总金额（元）大于等于<el-input-number v-model="item.startAmount" :min="index === 0 ? 0 : dataForm.companyPaymentTypes[index - 1].endAmount" disabled style="width: 120px" v-on:change="changeStartAmount" :controls="false"/>
          <template v-if="index !== dataForm.companyPaymentTypes.length - 1">
          小于<el-input-number v-model="item.endAmount" style="width: 120px" :min="item.startAmount + 1" max="999999999" :controls="false" v-on:change="changeEndAmount" :disabled="index === dataForm.companyPaymentTypes.length - 1"/>
          </template>
          时，按照
          <el-select v-model="item.type" style="width: 130px">
            <el-option
              v-for="item in companyPaymentTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <template v-if="item.type === 1">
            <el-input-number v-model="item.amount" style="width: 80px" min="0" max="999999999" :controls="false"/>元
          </template>
          <template v-if="item.type === 2">
            <el-input-number v-model="item.percent" style="width: 80px" min="0" max="999" :controls="false"/>
            <span style="font-weight: bold;font-size: 18px">‰</span>
          </template>
          收费
          <el-button icon="el-icon-minus" circle @click="removeCompanyPaymentType(index)" size="mini" style="margin-left: 10px" v-if="index === dataForm.companyPaymentTypes.length - 1 && index !== 0"></el-button>
        </el-row>
      </el-row>
      <el-form-item prop="companyType" :label="$t('company.companyType')">
        <el-select v-model="dataForm.type" :value="dataForm.type"
                   placeholder="请选择公司类型"
                   style=" width: 180px;">
          <el-option
                  v-for="item in companyTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="contactMail" :label="$t('company.contactMail')">
        <el-input v-model="dataForm.contactMail" :placeholder="$t('company.contactMail')" />
      </el-form-item>
      <el-form-item prop="address" :label="$t('company.address')">
        <el-input v-model="dataForm.address" :placeholder="$t('company.address')"/>
      </el-form-item>
      <el-form-item prop="remark" :label="$t('remark')">
        <el-input type="textarea" v-model="dataForm.remark" :placeholder="$t('remark')"/>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { debounce } from 'lodash'
  export default {
    data () {
      return {
        visible: false,
        menuList: [],
        deptList: [],
        paymentMethodOptions:[{//付费方式（1客户付费 2企业预存账户扣除）
          label: '客户付费',
          value: 1,
        }, {
          label: '企业账户余额',
          value: 2,
        }

        ],
        paymentTypeOptions:[{//付费类型（1按合同模板付费2按合同金额区间付费）
          label: '按合同模板付费',
          value: 1,
        }, {
          label: '按合同金额区间付费',
          value: 2,
        }

        ],
        companyPaymentTypeOptions: [
          {
            label: '固定金额',
            value: 1
          },
          {
            label: '合同总金额',
            value: 2
          }

        ],
        companyTypes:[{//公司类型 1合作公司 3担保公司 4其他企业
          label: '合作公司',
          value: 1,
        }, {
          label: '担保公司',
          value: 3,
        },{
          label: '其他企业',
          value: 4,
        }],
        dataForm: {
          id: '',
          name: '',
          regCode: '',
          legalPerson:'',
          legalPersonMobile:'',
          legalPersonIdentity:'',
          paymentMethod: 1,
          paymentType: 1,
          contractCode:'HB-WH',
          contactMobile:'',
          contactMail:'',
          type:1,
          address: '',
          remark:'',
          companyPaymentTypes: [
            {
              startAmount: 0,
              endAmount: 500000,
              type: 1,
              amount: 300,
              percent: 2
            },
            {
              startAmount: 500000,
              endAmount: 1000000,
              type: 1,
              amount: 1000,
              percent: 2
            },
            {
              startAmount: 1000000,
              endAmount: -1,
              type: 2,
              amount: 1500,
              percent: 10
            }
          ]
        }
      }
    },
    computed: {
      dataRule () {
        return {
          name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          regCode: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          contactMobile: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          legalPersonIdentity: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          contractCode: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]


        }
      }
    },
    methods: {
      init () {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          Promise.all([

          ]).then(() => {
            if (this.dataForm.id) {
              this.getInfo()
            }
          })
        })
      },
      // 获取信息
      getInfo () {
        this.$axios.get(`/manager/company/info/${this.dataForm.id}`).then(res => {
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          this.dataForm.menuIdList.forEach(item => this.$refs.menuListTree.setChecked(item, true))
          this.$refs.deptListTree.setCheckedKeys(this.dataForm.deptIdList)
        }).catch(() => {})
      },
      // 表单提交
      dataFormSubmitHandle: debounce(function () {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) {
            return false
          }
          // this.dataForm.menuIdList = JSON.stringify(this.dataForm.menuIdList)
          this.$http.json('/manager/company/addOrUpdate', this.dataForm).then(res => {
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          }).catch(() => {})
        })
      }, 1000, { 'leading': true, 'trailing': false }),
      removeCompanyPaymentType (index) {
        this.dataForm.companyPaymentTypes.splice(index, 1)
        this.dataForm.companyPaymentTypes[index - 1].endAmount = -1
      },
      addCompanyPaymentType () {
        this.dataForm.companyPaymentTypes.push({
          startAmount: null,
          endAmount: -1,
          type: 1,
          amount: 100,
          percent: null
        })
      },
      changeEndAmount (currentValue, oldValue) {
        for (let i in this.dataForm.companyPaymentTypes) {
          if (currentValue === this.dataForm.companyPaymentTypes[i].endAmount) {
            if (parseInt(i) === this.dataForm.companyPaymentTypes.length - 1) {
              this.dataForm.companyPaymentTypes[i].endAmount = -1
            } else {
              this.dataForm.companyPaymentTypes[parseInt(i) + 1].startAmount = currentValue
              this.changeStartAmount(currentValue, oldValue)
            }
          }
        }
      },
      changeStartAmount (currentValue, oldValue) {
        for (let i in this.dataForm.companyPaymentTypes) {
          if (currentValue === this.dataForm.companyPaymentTypes[i].startAmount) {
            if (this.dataForm.companyPaymentTypes[i].startAmount >= this.dataForm.companyPaymentTypes[i].endAmount) {
              this.dataForm.companyPaymentTypes[i].endAmount = this.dataForm.companyPaymentTypes[i].startAmount + 1
              this.changeEndAmount(this.dataForm.companyPaymentTypes[i].endAmount, oldValue)
            }
          }
        }
      }
    }
  }
</script>
